<template>
  <div>
    <el-card>
      <div style="margin-left: 20px">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="分类">
            <el-cascader v-model="searchData.categoryIds" :props="props" placeholder="请选择"/>
          </el-form-item>
          <el-form-item label="规格名称">
            <el-input v-model="searchData.specName" placeholder="请输入规格名称" clearable/>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" :icon="Search" @click="initData">搜索</el-button>
            <el-button size="small" :icon="Refresh" @click="reSpec">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button size="small" type="primary" :icon="Plus" @click="showDialog" plain>新增</el-button>
        <!--        <el-button size="small" type="success" :icon="Edit" plain>修改</el-button>-->
        <el-button size="small" type="danger" :icon="Delete" plain @click="delSpec">批量删除</el-button>
        <el-button :icon="Search" circle style="margin-left: 900px"/>
        <el-button :icon="Refresh" circle style="margin-left: 10px"/>
      </div>
      <div style="margin-top: 10px">
        <el-table :data="specs.specPageList" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column label="分类名称" property="categoryName" width="200"/>
          <el-table-column label="规格名称" property="specName" width="200"/>
          <el-table-column label="规格值" property="specValue">
            <template #default="scope">
              <div v-for="item in scope.row.specValue">
                {{ item.key }} :
                <el-tag style="background-color: cyan" v-for="val in item.valueList">{{ val }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" property="createTime"/>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button size="small" type="primary" text :icon="Edit" @click="showBrand(scope.row)">修改
              </el-button>
              <el-button size="small" type="danger" text :icon="Delete" @click="delSpec(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <pagination
            v-show="searchData.total > 0"
            :total="searchData.total"
            v-model:page="searchData.pageNum"
            v-model:limit="searchData.pageSize"
            @pagination="initData"/>
      </template>
    </el-card>

    <el-dialog v-model="dialogFormVisible" :title="title" width="500">
      <el-form :model="spec" ref="specForm" :rules="myRules" label-width="120px">
        <el-form-item label="分类" :rules="myRules.categoryIdList">
          <el-cascader v-model="spec.categoryIdList" :props="props" placeholder="请选择" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="规格名称" :rules="myRules.specName">
          <el-input v-model="spec.specName" placeholder="请输入规格名称" clearable style="width: 300px"/>
        </el-form-item>
        <el-form-item label="规格值" :rules="myRules.specValue">
          <el-row v-if="specValueList && specValueList.length > 0" v-for="(item,index) in specValueList"
                  style="width: 100%">
            {{ item.key }} :
            <el-tag style="background-color: cyan" v-for="val in item.valueList">{{ val }}</el-tag>
            <el-button size="small" @click="removeOne(index)">删除</el-button>
          </el-row>
          <el-row v-if="!specValueData">
            <el-button @click="specValueData = {}">添加新规格</el-button>
          </el-row>
          <el-row v-else>
            <el-col :span="6">
              <el-input v-model="specValueData.key" placeholder="规格" clearable/>
            </el-col>
            <el-col :span="14">
              <el-input v-model="specValueData.valueList" placeholder="规格值:例如:白色,黑色" clearable/>
            </el-col>
            <el-col :span="4">
              <el-button @click="addSpecValue">添加</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="warning" @click="dialogFormVisible = false">取消</el-button>
          <el-button type="success" @click="addOrUpdate()">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {specList, delSpecs, saveOrUpdateSpec, getSpec} from "@/api/product/spec.js";
import {Search, Refresh, Plus, Edit, Delete} from '@element-plus/icons-vue'
import {specPinia} from "@/store/product/specPinia.js"
import {categoryList} from "@/api/product/category.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {reactive, onMounted, ref} from 'vue'

let specs = specPinia()
/*=====================================搜索==========================================*/
//搜索条件
let searchData = reactive({
  categoryId: null,
  specName: '',
  pageNum: 1,
  pageSize: 5,
  total: 0,
  categoryIds: []
})
//分类-懒加载-级联选择器
const props = {
  lazy: true,
  label: 'name',
  value: 'id',
  leaf: 'leaf',
  lazyLoad: async (node, resolve) => {
    let pid = 0
    if (node.data.id) {
      pid = node.data.id
    }
    let {data} = await categoryList(pid)
    data.forEach(item => item.leaf = !item.hasChildren)
    resolve(data)
  },
}
//重置
let reSpec = () => {
  searchData.name = ''
  searchData.pageNum = 1
  searchData.pageSize = 5
  searchData.total = 0
  searchData.categoryId = null
  initData()
}
/*======================================列表=========================================*/
//分页
let initData = async () => {
  if (searchData.categoryIds && searchData.categoryIds.length === 3) {
    searchData.categoryId = searchData.categoryIds[2]
  }
  let {rows, total} = await specList(searchData)
  rows.forEach(item => item.specValue = JSON.parse(item.specValue))
  specs.specPageList = rows
  searchData.total = total
}
//页面加载
onMounted(() => {
  initData()
})
/*========================================批量删除==========================================*/
let ids = ref([])
let handleSelectionChange = (rows) => {
  ids.value = rows.map(item => item.id)
}
let delSpec = async (row) => {
  let idList = row.id || ids.value
  ElMessageBox.confirm('确定删除吗?', '提示', {confirmButtonText: '确认', cancelButtonText: '取消'}).then(async () => {
    try {
      await delSpecs(idList)
      ElMessage.success('删除成功')
      await initData()
    } catch (e) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.warning('取消删除')
  })
}
/*========================================添加|修改==========================================*/
let spec = ref({})
let title = ref('')
let dialogFormVisible = ref(false)
//对话框弹出的方法
let showDialog = () => {
  title.value = '添加分类品牌'
  clearDialog()
  dialogFormVisible.value = true
}
//清空弹框
let clearDialog = () => {
  spec.value = {}
  specValueList.value = []
}
//定义规则
let myRules = reactive({
  categoryIdList: [
    {required: true, message: '请选择分类', trigger: 'change'}
  ],
  specName: [
    {required: true, message: '请输入规格名称', trigger: 'change'}
  ],
  specValue: [
    {required: true, message: '请输入规格值', trigger: 'change'}
  ]
})
//规格值列表
let specValueData = ref(null)
let specValueList = ref([])
let addSpecValue = () => {
  specValueData.value.valueList = specValueData.value.valueList.split(',')
  specValueList.value.push(specValueData.value)
  specValueData.value = null
}
let removeOne = (index) => {
  specValueList.value.splice(index, 1)
}
//添加或修改 数据
let specForm = ref()
let addOrUpdate = async () => {
  specForm.value.validate()
  try {
    if (spec.value.categoryIdList && spec.value.categoryIdList.length === 3) {
      spec.value.categoryId = spec.value.categoryIdList[2]
    }
    if (specValueList.value.length > 0) {
      spec.value.specValue = JSON.stringify(specValueList.value)
    }
    await saveOrUpdateSpec(spec.value)
    ElMessage.success(title.value + '成功')
    dialogFormVisible.value = false
    await initData()
    clearDialog()
  } catch (e) {
    ElMessage.error(title.value + '失败')
  }
}
//回显
let showBrand = async (row) => {
  let {data} = await getSpec(row.id)
  spec.value = data
  specValueList.value = JSON.parse(spec.value.specValue)
  title.value = '修改分类品牌'
  dialogFormVisible.value = true
}
</script>
<style scoped>

</style>